package models

import (
	"errmsg"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"time"
	"tools"
)

type Trip struct {
	Id         string `orm:"column(id);pk" json:"id" form:"id"`
	UserId     string `orm:"column(user_id)" json:"user_id" form:"user_id"`             // 用户id
	What       string `orm:"column(what)" json:"what" form:"what"`                      // 做什么
	Time       string `orm:"column(time)" json:"time" form:"time"`                      // 提醒时间
	Date       string `orm:"column(date)" json:"date" form:"date"`                      // 提醒日期
	Wkocc      string `orm:"column(wkocc)" json:"wkocc" form:"wkocc"`                   // 循环
	CreateTime int64  `orm:"column(create_time)" json:"create_time" form:"create_time"` // 存放时间
	Status     int    `orm:"column(status)" json:"status" form:"status"`
	To         string `orm:"column(to)" json:"to" form:"to"`                      // 提醒对象
	IsFinish   int64  `orm:"column(is_finish)" json:"is_finish" form:"is_finish"` // 是否完成
	Source     string `orm:"column(source)" json:"source" form:"source"`          // 提醒来源
	ToUser     *User  `orm:"-" json:"to_user"`
}

func (m *Trip) TableName() string {
	return "trip"
}

func init() {
	orm.RegisterModel(new(Trip))
}

func NewTrip() *Trip {
	return &Trip{}
}

func AddTrip(tp *Trip) error {
	tp.Id = tools.GUUID()
	tp.CreateTime = time.Now().Unix()

	// 数据入库
	if _, err := orm.NewOrm().Insert(tp); err != nil {
		logs.Error("AddTrip error:", err)
		return errmsg.ErrResponseSystem
	}
	return nil
}

func UpdateTrip(tp *Trip) error {
	// 数据入库
	if _, err := orm.NewOrm().Update(tp); err != nil {
		logs.Error("UpdateTrip error:", err)
		return errmsg.ErrResponseSystem
	}
	return nil
}

func GetTripById(id string) (*Trip, error) {
	var (
		tp  *Trip
		err error
	)
	tp = &Trip{Id: id}
	err = orm.NewOrm().Read(tp)
	if err == orm.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		logs.Error("GetTripById error:", err)
		return nil, errmsg.ErrResponseSystem
	}
	tp.ToUser, _ = GetUserById(tp.To)
	return tp, nil
}

func DelTrip(uid, id string) error {
	_, err := orm.NewOrm().QueryTable(NewTrip().TableName()).Filter("id", id).Filter("user_id", uid).Delete()
	if err != nil {
		logs.Error("DelTrip error:", err)
		return errmsg.ErrResponseSystem
	}
	return nil
}

func GetAllTripByUid(uid string, page int) ([]*Trip, error) {
	var (
		ls  []*Trip
		err error
		qs  orm.QuerySeter
	)

	qs = orm.NewOrm().QueryTable(NewTrip().TableName()).Filter("user_id", uid).OrderBy("-create_time")

	if page > 0 {
		row := beego.AppConfig.DefaultInt("page_limit", 20)
		start := (page - 1) * row
		qs = qs.Limit(row).Offset(start)
	}

	if _, err = qs.All(&ls); err != nil {
		logs.Error("GetAllTripByUid error:", err)
		return nil, errmsg.ErrResponseSystem
	}

	if len(ls) == 0 {
		return nil, nil
	}

	for k, v := range ls {
		ls[k].ToUser, _ = GetUserById(v.To)
	}

	return ls, nil
}
